package smartcampus.scjava.controller.seventh;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import org.springframework.web.bind.annotation.*;
import smartcampus.scjava.POJO.DO.seventh.Announcement;
import smartcampus.scjava.POJO.DO.seventh.User;
import smartcampus.scjava.service.seventh.AnnouncementService;
import smartcampus.scjava.service.seventh.UserService;
import smartcampus.scjava.utils.seventh.common.Result;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/api/announcement")
public class AnnouncementController {
    @Resource
    private AnnouncementService announcementService;
    @Resource
    private HttpServletRequest request;
    @Resource
    private UserService userService;

    public User getUser() {
        String token = request.getHeader("token");
        String username = JWT.decode(token).getAudience().get(0);
        return userService.getOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, username));
    }

    @PostMapping
    public Result<?> save(@RequestBody Announcement announcement) {
        announcementService.save(announcement);
        return Result.success();
    }

    @PutMapping
    public Result<?> update(@RequestBody Announcement announcement) {
        announcementService.updateById(announcement);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable Long id) {
        announcementService.removeById(id);
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result<?> findById(@PathVariable Long id) {
        return Result.success(announcementService.getById(id));
    }

    @GetMapping
    public Result<?> findAll() {
        List<Announcement> list = announcementService.list();
        return Result.success(list);
    }

    @GetMapping("/page")
    public Result<?> findPage(@RequestParam(required = false, defaultValue = "") String name,
                                                @RequestParam(required = false, defaultValue = "1") Integer pageNum,
                                                @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        LambdaQueryWrapper<Announcement> query = Wrappers.<Announcement>lambdaQuery().orderByDesc(Announcement::getId);
        if (StrUtil.isNotBlank(name)) {
            query.like(Announcement::getId, name);
        }
        IPage<Announcement> page = announcementService.page(new Page<>(pageNum, pageSize), query);
        return Result.success(page);
    }

}
